package com.lvmama.rhino.web;

import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.pojo.screen.OrderInfoData;
import com.lvmama.rhino.pojo.screen.Product;
import com.lvmama.rhino.service.ScreenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/6/12.
 */
@Controller
@RequestMapping("homePage")
public class HomeScreenController extends BaseControllerSupport {

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private ScreenService screenService;

    @RequestMapping("hotScenicSpot")
    @ResponseBody
    public Map<String,Object> hotScenicSpot( HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if(!jedisCluster.exists("rhino_orderList") || !jedisCluster.exists("rhino_productList")){
            return resultMap;
        }
        //热门景区数据
        List<Product> productList = screenService.getProductList();
        resultMap.put("productList", productList);
        //订单量数据
        List<OrderInfoData> orderList = screenService.getOrderList();
        resultMap.put("totalOrderQuantity", orderList.size());

        Map<String,OrderInfoData> map = new HashMap<String,OrderInfoData>();
        //合并重复数据
        for(OrderInfoData a : orderList){
            OrderInfoData obj = new OrderInfoData();
            String name = a.getProvince();
            if(a.isPay()){
                a.setPayCount(1l);
            }else{
                a.setPayCount(0l);
            }
            if(map.containsKey(name)){
                obj.setCount(map.get(name).getCount()+1l);
                obj.setPayCount(map.get(name).getPayCount()+a.getPayCount());
            }else{
                obj.setPayCount(a.getPayCount());
                obj.setCount(1l);
            }
            map.put(name, obj);
        }

        OrderInfoData unknownObj = new OrderInfoData();
        boolean unknownFlag0 = false;
        //生成新的list数组，省份与订单之间的关系
        List<OrderInfoData> newList= new ArrayList<OrderInfoData>();
        for(Map.Entry<String, OrderInfoData> entry:map.entrySet()){
            OrderInfoData a=new OrderInfoData();
            String province = entry.getKey();
            Long count = entry.getValue().getCount();
            Long payCount = entry.getValue().getPayCount();
            if("".equals(province)){
                unknownObj.setProvince("未知");
                unknownObj.setCount(count);
                unknownObj.setPayCount(payCount);
                unknownFlag0 = true;
                continue;
            }
            a.setProvince(province);
            a.setCount(count);
            a.setPayCount(payCount);
            //entry.getKey(),entry.getValue()
            newList.add(a);
        }

        //根据订单量降序排序
        Collections.sort(newList, new Comparator<OrderInfoData>() {
            @Override
            public int compare(OrderInfoData o1, OrderInfoData o2) {
                long count1 = o1.getCount().longValue();
                long count2 = o2.getCount().longValue();
                if(count1<count2)
                    return 1;
                else if(count1>count2)
                    return -1;
                else
                    return 0;
            }
        });

        for(OrderInfoData orderInfoData :newList){
            String province = orderInfoData.getProvince();
            province=matchProvince(province);
            orderInfoData.setProvince(province);
        }

        int count = newList.size();
        //y轴省份城市
        String[] orderProvince = null;
        //支付完成量
        Long[] payComplete = null;
        //订单量
        Long[] orderQuantity = null;
        if(count > 10){
            orderProvince = new String[11];
            payComplete = new Long[11];
            orderQuantity = new Long[11];
        }else{
            orderProvince = new String[count];
            payComplete = new Long[count];
            orderQuantity = new Long[count];
        }

        //地区订单
        Long other = 0l;
        Long otherPayComplete = 0l;
        Long otherOrderQuantity = 0l;
        for(int i=0;i<count;i++){
            String province = newList.get(i).getProvince();
            Long amount = newList.get(i).getCount();
            Long payCount = newList.get(i).getPayCount();
            if(i < 10){
                orderProvince[i] = province;
                payComplete[i] = payCount;
                orderQuantity[i] = amount;
            }else{
                other +=  amount;
                otherPayComplete +=  payCount;
                otherOrderQuantity +=  amount;
            }
        }
        if( count> 10){
            orderProvince[10] = "其他";
            if(unknownFlag0){
                payComplete[10] = otherPayComplete+unknownObj.getPayCount();
                orderQuantity[10] = otherOrderQuantity+unknownObj.getCount();
            }else {
                payComplete[10] = otherPayComplete;
                orderQuantity[10] = otherOrderQuantity;
            }
        }else if(count == 10){
            if(unknownFlag0){
                orderProvince[9] = "其他";
                payComplete[9] += unknownObj.getPayCount();
                orderQuantity[9] += unknownObj.getCount();
            }
        }else {
            if(unknownFlag0){
                orderProvince[count] = "其他";
                payComplete[count] = unknownObj.getPayCount();
                orderQuantity[count] = unknownObj.getCount();
            }
        }

        //订单占比
        Long other1 = 0l;
        List<Map<String, Object>> provinceSeriesList = new ArrayList<Map<String, Object>>();
        for(int i=0;i<count;i++){
            Map<String, Object> orderMap = new HashMap<String, Object>();
            String province = newList.get(i).getProvince();
            Long amount = newList.get(i).getCount();
            if(i < 7){
                orderMap.put("name", province);
                orderMap.put("value", amount);
                provinceSeriesList.add(orderMap);
            }else{
                other1 +=  amount;
            }
        }
        Map<String, Object> mapOther = new HashMap<String, Object>();
        if( count > 7){
            mapOther.put("name", "其他");
            if(unknownFlag0){
                mapOther.put("value", other1 + unknownObj.getCount());
            }else {
                mapOther.put("value", other1);
            }
            provinceSeriesList.add(mapOther);
        }else if (count == 7){
            if(unknownFlag0){
                mapOther.put("name", "其他");
                mapOther.put("value", Long.valueOf(provinceSeriesList.get(count - 1).get("value").toString()) + unknownObj.getCount());
                provinceSeriesList.add(mapOther);
            }
        }else {
            if(unknownFlag0){
                mapOther.put("name", "其他");
                mapOther.put("value", unknownObj.getCount());
                provinceSeriesList.add(mapOther);
            }
        }


        resultMap.put("payComplete", payComplete);//支付完成量
        resultMap.put("orderQuantity", orderQuantity);//订单量

        resultMap.put("provinceLegend", orderProvince);//Y轴省份
        resultMap.put("provinceSeries", provinceSeriesList);//省份的订单占比

        resultMap.put("newList", newList);//地图数据


        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (OrderInfoData obj : orderList){
            Date date = obj.getOrderDate();
            String dateStr = sdf0.format(date);
            Date newDate = null;
            try {
                newDate = sdf1.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            obj.setOrderDate(newDate);
        }
        Map<String,OrderInfoData> mapProvince = new HashMap<String,OrderInfoData>();
        //根据订单时间合并排序
        for(OrderInfoData a : orderList){
            Date dateLine = a.getOrderDate();
            String operator = a.getOperator();
            String name = sdf0.format(dateLine);
            OrderInfoData childObj = new OrderInfoData();
            if(mapProvince.containsKey(name)){
                childObj = mapProvince.get(name);
                if(operator.equals("CM")){
                    Long CMOrderCount = childObj.getCMOrderCount()==null?0:childObj.getCMOrderCount();
                    childObj.setCMOrderCount(CMOrderCount+1l);
                }else if(operator.equals("CU")){
                    Long CUOrderCount = childObj.getCUOrderCount()==null?0:childObj.getCUOrderCount();
                    childObj.setCUOrderCount(CUOrderCount+1l);
                }else if(operator.equals("CT")){
                    Long CTOrderCount = childObj.getCTOrderCount()==null?0:childObj.getCTOrderCount();
                    childObj.setCTOrderCount(CTOrderCount+1l);
                }else{
                    Long otherOrderCount = childObj.getOtherOrderCount()==null?0:childObj.getOtherOrderCount();
                    childObj.setOtherOrderCount(otherOrderCount+1l);
                }
            }else{
                if(operator.equals("CM")){
                    childObj.setCMOrderCount(1l);
                }else if(operator.equals("CU")){
                    childObj.setCUOrderCount(1l);
                }else if(operator.equals("CT")){
                    childObj.setCTOrderCount(1l);
                }else {
                    childObj.setOtherOrderCount(1l);
                }
            }
            mapProvince.put(name, childObj);
        }
        List<OrderInfoData> newDateList= new ArrayList<OrderInfoData>();
        for(Map.Entry<String, OrderInfoData> entry:mapProvince.entrySet()){
            OrderInfoData a=new OrderInfoData();
            Date newDate = null;
            try {
                newDate = sdf1.parse(entry.getKey());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            a.setOrderDate(newDate);
            a.setCMOrderCount(entry.getValue().getCMOrderCount()==null?0l:entry.getValue().getCMOrderCount());
            a.setCUOrderCount(entry.getValue().getCUOrderCount()==null?0l:entry.getValue().getCUOrderCount());
            a.setCTOrderCount(entry.getValue().getCTOrderCount()==null?0l:entry.getValue().getCTOrderCount());
            a.setOtherOrderCount(entry.getValue().getOtherOrderCount()==null?0l:entry.getValue().getOtherOrderCount());
            //entry.getKey(),entry.getValue()
            newDateList.add(a);
        }
        //根据时间升序排序
        Collections.sort(newDateList, new Comparator<OrderInfoData>() {
            @Override
            public int compare(OrderInfoData o1, OrderInfoData o2) {
                long time1 = o1.getOrderDate().getTime();
                long time2 = o2.getOrderDate().getTime();
                if(time1<time2)
                    return -1;
                else if(time1>time2)
                    return 1;
                else
                    return 0;
            }
        });

        int listCount = newDateList.size();
        String[] orderTime = new String[listCount];
        Long[] CMOrder = new Long[listCount];
        Long[] CUOrder = new Long[listCount];
        Long[] CTOrder = new Long[listCount];
        Long[] otherOrder = new Long[listCount];
        for (int i=0 ;i<listCount;i++){
            Date date = newDateList.get(i).getOrderDate();
            String dateNowStr = sdf.format(date);
            orderTime[i]=dateNowStr;
            CMOrder[i]=newDateList.get(i).getCMOrderCount();
            CUOrder[i]=newDateList.get(i).getCUOrderCount();
            CTOrder[i]=newDateList.get(i).getCTOrderCount();
            otherOrder[i]=newDateList.get(i).getOtherOrderCount();
        }
        resultMap.put("orderTime", orderTime);//运营商订单X轴时间
        resultMap.put("CMOrder", CMOrder);//移动运营商订单量
        resultMap.put("CUOrder", CUOrder);//联通运营商订单量
        resultMap.put("CTOrder", CTOrder);//电信运营商订单量
        resultMap.put("otherOrder", otherOrder);//其他订单量


        Map<String,Map<String,Long>> mapTiming = new HashMap<String,Map<String,Long>>();
        String[] provinceArr = new String[]{"北京","天津","河北","山西","内蒙古","辽宁","吉林","黑龙江",
                "","江苏","浙江","安徽","福建","江西","山东","河南",
                "湖北","湖南","广东","广西","海南","重庆","四川","贵州",
                "云南","西藏","陕西","甘肃","青海","宁夏","新疆"};
        //根据下单时间合并数据
        for(OrderInfoData a : orderList){
            Date dateLine = a.getOrderDate();
            String province = a.getProvince();
            String name = sdf0.format(dateLine);
            province=matchProvince(province);
            Map<String,Long> childMap = new HashMap<String,Long>();
            if(mapTiming.containsKey(name)){
                childMap = mapTiming.get(name);
                if(childMap.containsKey(province)){
                    childMap.put(province,childMap.get(province)+1l);
                }else{
                    childMap.put(province,1l);
                }
            }else{
                childMap.put(province,1l);
            }
            mapTiming.put(name, childMap);
        }
        List<Date> timeList = new ArrayList<Date>();
        for(Map.Entry<String, Map<String,Long>> entry:mapTiming.entrySet()){
            String dateNowStr = entry.getKey();
            Date newDate = null;
            try {
                newDate = sdf1.parse(dateNowStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            timeList.add(newDate);
        }
        //根据下单时间升序排序
        Collections.sort(timeList, new Comparator<Date>() {
            @Override
            public int compare(Date o1, Date o2) {
                long time1 = o1.getTime();
                long time2 = o2.getTime();
                if(time1<time2)
                    return -1;
                else if(time1>time2)
                    return 1;
                else
                    return 0;
            }
        });

        Map<String,Long[]> dataMap = new HashMap<String,Long[]>();
        Map<String,String[]> provinceMap = new HashMap<String,String[]>();
        String[] XAxisList = new String[timeList.size()];
        for(int j =0;j< timeList.size();j++){
            Date date = timeList.get(j);
            String dateStr = sdf0.format(date);
            Map<String,Long> childMap = mapTiming.get(dateStr);
            List<OrderInfoData> orderInfoDataList = new ArrayList<OrderInfoData>();
            OrderInfoData unknownObj1 = new OrderInfoData();
            boolean unknownFlag = false;
            for(Map.Entry<String, Long> entry:childMap.entrySet()){
                OrderInfoData orderInfoData = new OrderInfoData();
                String province = entry.getKey();
                Long countValue = entry.getValue();
                if("".equals(province)){
                    unknownObj1.setProvince("未知");
                    unknownObj1.setCount(countValue);
                    unknownFlag = true;
                    continue;
                }
                orderInfoData.setProvince(province);
                orderInfoData.setCount(countValue);
                orderInfoDataList.add(orderInfoData);
            }
            Collections.sort(orderInfoDataList, new Comparator<OrderInfoData>() {
                @Override
                public int compare(OrderInfoData o1, OrderInfoData o2) {
                    long count1 = o1.getCount();
                    long count2 = o2.getCount();
                    if(count2<count1)
                        return -1;
                    else if(count2>count1)
                        return 1;
                    else
                        return 0;
                }
            });
            int count0 = orderInfoDataList.size();
            Long otherCount = 0l;
            if(count0 > 10){
                for(int i = 10;i < count0; i++){
                    otherCount += orderInfoDataList.get(i).getCount();
                }
                orderInfoDataList = orderInfoDataList.subList(0,10);
                OrderInfoData orderInfoData10 = new OrderInfoData();
                orderInfoData10.setProvince("其他");
                if(unknownFlag){
                    orderInfoData10.setCount(otherCount + unknownObj1.getCount());
                }else {
                    orderInfoData10.setCount(otherCount);
                }
                orderInfoDataList.add(orderInfoData10);
            }else if(count0 == 10){
                if(unknownFlag){
                    OrderInfoData lastObj = orderInfoDataList.get(count0 - 1);
                    lastObj.setProvince("其他");
                    lastObj.setCount(lastObj.getCount() + unknownObj1.getCount());
                }
            }else {
                if(unknownFlag){
                    OrderInfoData lastObj = new OrderInfoData();
                    lastObj.setProvince("其他");
                    lastObj.setCount(unknownObj1.getCount());
                    orderInfoDataList.add(lastObj);
                }
            }

            int size0 = orderInfoDataList.size();
            Long[] countArr = new Long[size0];
            String[] provArr =new String[size0];
            for(int i=0;i<size0;i++){
                provArr[i]=orderInfoDataList.get(i).getProvince();
                countArr[i]=orderInfoDataList.get(i).getCount();
            }
            String dateXAxisStr = sdf.format(date);
            XAxisList[j]=dateXAxisStr;
            provinceMap.put(dateXAxisStr,provArr);
            dataMap.put(dateXAxisStr,countArr);
        }
        resultMap.put("XAxisList",XAxisList);//时间轴
        resultMap.put("orderDataMap",dataMap);//订单统计数据
        resultMap.put("provinceMap",provinceMap);//省份数据

        /*Map<String,Long[]> dataMap = new HashMap<String,Long[]>();
        String[] XAxisList = new String[timeList.size()];
        for(int j =0;j< timeList.size();j++){
            Date date = timeList.get(j);
            String dateStr = sdf0.format(date);
            Map<String,Long> childMap = mapTiming.get(dateStr);
            Long[] countArr = new Long[provinceArr.length];
            for(int i = 0;i<provinceArr.length;i++){
                String key = provinceArr[i];
                Long orderCount = 0l;
                if(childMap.containsKey(key)){
                    orderCount = childMap.get(key);
                }
                countArr[i]=orderCount;
            }
            String dateXAxisStr = sdf.format(date);
            XAxisList[j]=dateXAxisStr;
            dataMap.put(dateXAxisStr,countArr);
        }
        resultMap.put("XAxisList",XAxisList);//时间轴
        resultMap.put("orderDataMap",dataMap);//订单统计数据*/

        return resultMap;
    }

    public String matchProvince(String province){
        if(province.indexOf("宁夏")!=-1){
            province = "宁夏";
        }else if(province.indexOf("新疆")!=-1){
            province = "新疆";
        }else if(province.indexOf("内蒙古")!=-1){
            province = "内蒙古";
        }else if(province.indexOf("西藏")!=-1){
            province = "西藏";
        }else if(province.indexOf("广西")!=-1){
            province = "广西";
        }else if(province.indexOf("香港")!=-1){
            province = "香港";
        }else if(province.indexOf("澳门")!=-1){
            province = "澳门";
        }
        return province;
    }

}
